package com.shijie.sjoj.service.core;

import com.shijie.sjoj.model.api.user.UserSecurityService;
import com.shijie.sjoj.model.component.CryptoModel;
import com.shijie.sjoj.model.component.validate.NumberValidate;
import com.shijie.sjoj.model.component.validate.RegexValidate;
import com.shijie.sjoj.model.exception.UserException;
import com.shijie.sjoj.model.pojo.entity.User;
import com.shijie.sjoj.service.mapper.UserSecurityMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

/**
 * 用户安全服务接口实现类
 *
 * @author ZSJ
 */
@Slf4j
@DubboService
@RequiredArgsConstructor
public class UserSecurityServiceImpl implements UserSecurityService {

    private final UserSecurityMapper userSecurityMapper;

    @Override
    public User obtainPassword(User user) {
        // 无效值校验
        if (NumberValidate.invalidSys(user.getUserId()) || RegexValidate.invalidSysAccount(user.getAccount())) {
            throw UserException.throwError("无效的用户id或账号");
        }
        // 获取密码
        return userSecurityMapper.obtainPassword(user);
    }

    @Override
    public boolean newPassword(User user) {
        // 无效值校验
        if (NumberValidate.invalidSys(user.getUserId()) || RegexValidate.invalidSysAccount(user.getAccount())) {
            throw UserException.throwError("无效的用户id或账号");
        }
        if (RegexValidate.invalidSysPassword(user.getPassword())) {
            throw UserException.throwError("无效的新密码");
        }
        // 密码格式化
        user.setPassword(CryptoModel.encryptPassword(user.getPassword()));
        // 设置新密码
        return userSecurityMapper.newPassword(user);
    }

    @Override
    public boolean replacePhone(User user) {
        // 无效值校验
        if (NumberValidate.invalidSys(user.getUserId()) || RegexValidate.invalidSysAccount(user.getAccount())) {
            throw UserException.throwError("无效的用户id或账号");
        }
        if (RegexValidate.invalidDefPhone(user.getPhone())) {
            throw UserException.throwError("无效的手机号");
        }
        // 更换手机号
        return userSecurityMapper.newPassword(user);
    }


}
